package com.x52im.rainbowchat.im;

import com.x52im.rainbowchat.BaseConf;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisDateSource {
    private static JedisDateSource INSTANCE;
    private static JedisPool jedisPool = null;

    private static synchronized JedisPool createJedisPool() {
        if (jedisPool == null) {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxIdle(30);
            config.setTestOnBorrow(true);
            jedisPool = new JedisPool(config, BaseConf.getInstance().getREDIS_HOST(), BaseConf.getInstance().getREDIS_PORT());
        }
        return jedisPool;
    }

    public static JedisDateSource getInstance() {
        if (INSTANCE == null) {
            synchronized (JedisDateSource.class) {
                if (INSTANCE == null) {
                    INSTANCE = new JedisDateSource();
                }
            }
        }
        if (jedisPool == null) {
            createJedisPool();
        }
        return INSTANCE;
    }

    public static Jedis getResource() {
        if (jedisPool != null) {
            return jedisPool.getResource();
        }
        return null;
    }

    public static JedisPool getJedisPool() {
        if (jedisPool != null) {
            return jedisPool;
        }
        return null;
    }

    public static void returnResource(Jedis jedis) {
        if (jedisPool != null) {
            jedisPool.returnResource(jedis);
        }
    }
}
